'use strict';

define(['controllers', '../service/collectionService', '../service/replicaService', '../service/configService', '../service/nodeService', 'bootstrap-switch'], function (controllers) {
    controllers.solr.register('CollectionController', ['$scope', 'CollectionService', 'ReplicaService', 'ConfigService', 'NodeService', function ($scope, collectionService, replicaService, configService, nodeService) {
        $scope.init = function () {
            $scope.pageNo = 1;
            $scope.pageSize = 10;

            configService.query(function (config) {
                $scope.configs = config[0].children;
                $scope.configMap = {};
                for (var i = 0; i < $scope.configs.length; i++) {
                    $scope.configMap[$scope.configs[i].id] = $scope.configs[i];
                }
            });
            $scope.nodes = nodeService.findAll(function (nodes) {
                $scope.nodeMap = {};
                for (var i = 0; i < nodes.length; i++) {
                    $scope.nodeMap[nodes[i].id] = nodes[i];
                }
            });
            $scope.save_replicas = [];
            $scope.save_err = false;
        };

        $scope.initEvent = function () {
            $('#editDialog').on('shown.bs.modal', function () {
                if ($scope.save_id == null) {
                    $('#save_name').select();
                } else {
                    $('#save_remark').select();
                }
            });
            $('#save_name').keypress(function (e) {
                if (isSubmitKeyCode(e)) {
                }
            });
        };

        $scope.query = function (pageNo) {
            if (pageNo != null) {
                $scope.pageNo = pageNo;
            }
            collectionService.query({
                name: $scope.query_name,
                pageNo: $scope.pageNo,
                pageSize: $scope.pageSize
            }, function (data) {
                $scope.paged = data.paged;
                $scope.docsMap = data.docsMap;
            });
        };

        $scope.setEditForm = function (collection) {
            collection = collection == null ? {} : collection;
            $scope.save_id = collection.id;
        };

        $scope.allowCommitSwitch = null;
        $scope.allowRollbackSwitch = null;
        $scope.edit = function (collection) {
            if (collection != null) {
                $scope.save_id = collection.id;
                $scope.save_name = collection.name;
                $scope.save_config = collection.config;
                $scope.save_allowCommit = collection.allowCommit != null ? collection.allowCommit : false;
                $scope.save_allowRollback = collection.allowRollback != null ? collection.allowRollback : false;
                $scope.save_maxStart = collection.maxStart != null ? collection.maxStart : 1000;
                $scope.save_maxLimit = collection.maxLimit != null ? collection.maxLimit : 100;
                $scope.save_remark = collection.remark;
                $scope.save_replicas = replicaService.queryByCollectionId({collectionId: collection.id});
            } else {
                $scope.save_id = null;
                $scope.save_name = '';
                $scope.save_config = null;
                $scope.save_allowCommit = false;
                $scope.save_allowRollback = false;
                $scope.save_maxStart = 1000;
                $scope.save_maxLimit = 100;
                $scope.save_remark = '';
                $scope.save_replicas = [];
            }
            if ($scope.allowCommitSwitch == null) {
                $scope.allowCommitSwitch = $("#save_allowCommit");
                $scope.allowCommitSwitch.bootstrapSwitch();
                $scope.allowCommitSwitch.on('switchChange.bootstrapSwitch', function (event, state) {
                    $scope.save_allowCommit = state;
                });
            }
            if ($scope.allowRollbackSwitch == null) {
                $scope.allowRollbackSwitch = $("#save_allowRollback");
                $scope.allowRollbackSwitch.bootstrapSwitch();
                $scope.allowRollbackSwitch.on('switchChange.bootstrapSwitch', function (e, state) {
                    $scope.save_allowRollback = state;
                });
            }
            $scope.allowCommitSwitch.bootstrapSwitch('state', $scope.save_allowCommit);
            $scope.allowRollbackSwitch.bootstrapSwitch('state', $scope.save_allowRollback);
            $('#editDialog').modal('show');
        };

        $scope.addReplica = function () {
            $scope.save_replicas.push({
                coreName: $scope.save_name,
                shard: 'shard1'
            });
        };

        $scope.delReplica = function (idx) {
            $scope.save_replicas.removeAt(idx);
        };

        $scope.validName = function () {
            if (isEmpty($scope.save_name)) {
                $scope.save_errMsg = '集合名称不能为空';
                return false;
            }
            if (collectionService.exist($scope.save_name, $scope.save_id)) {
                $scope.save_errMsg = '集合名称已经存在';
                return false;
            }
            return true;
        };

        $scope.validConfig = function () {
            if (isEmpty($scope.save_config)) {
                $scope.save_errMsg = '配置文件不能为空';
                return false;
            }
            return true;
        };

        $scope.validReplicas = function () {
            var saveReplicaMap = {};
            for (var i = 0; i < $scope.save_replicas.length; i++) {
                var replica = $scope.save_replicas[i];
                var replicaKey = replica.coreName + replica.nodeId;
                if (saveReplicaMap[replicaKey] != null) {
                    $scope.save_errMsg = '集群配置不能重复';
                    return false;
                }
                saveReplicaMap[replicaKey] = replica;
            }
            return true;
        };

        $scope.saving = false;
        $scope.save = function () {
            $scope.saving = true;
            $scope.save_err = false;
            $scope.save_errMsg = '';

            if ($scope.validName() && $scope.validConfig() && $scope.validReplicas()) {
                var shardReplicas = {};
                for (var i = 0; i < $scope.save_replicas.length; i++) {
                    var replica = $scope.save_replicas[i];
                    if (shardReplicas[replica.shard] == null) {
                        shardReplicas[replica.shard] = [];
                    }
                    shardReplicas[replica.shard].push({
                        coreName: replica.coreName,
                        nodeId: replica.nodeId
                    });
                }
                collectionService.save({
                    id: $scope.save_id
                }, {
                    name: $scope.save_name,
                    config: $scope.save_config,
                    allowCommit: $scope.save_allowCommit,
                    allowRollback: $scope.save_allowRollback,
                    maxStart: $scope.save_maxStart,
                    maxLimit: $scope.save_maxLimit,
                    remark: $scope.save_remark,
                    shardReplicas: shardReplicas
                }, function () {
                    $('#editDialog').modal('hide');
                    $scope.saving = false;
                    $scope.setEditForm(null);
                    $scope.query();
                });
            } else {
                $scope.save_err = true;
            }
        };

        $scope.confirmRemove = function (collection) {
            $scope.removeId = collection.id;
            $('#removeDialog').modal('show');
        };

        $scope.remove = function () {
            collectionService.remove({id: $scope.removeId}, function () {
                $scope.removeId = null;
                $('#removeDialog').modal('hide');
                $scope.query();
            });
        };

        $scope.confirmReload = function (collection) {
            $scope.reloadId = collection.id;
            $('#reloadDialog').modal('show');
        };

        $scope.reload = function () {
            collectionService.reload({id: $scope.reloadId}, function () {
                $scope.reloadId = null;
                $('#reloadDialog').modal('hide');
                $scope.query();
            });
        };

        $scope.confirmOptimize = function (collection) {
            $scope.optimizeId = collection.id;
            $('#optimizeDialog').modal('show');
        };

        $scope.optimize = function () {
            collectionService.optimize({
                id: $scope.optimizeId,
                maxSegments: $scope.optimize_maxSegments
            }, function () {
                $scope.reloadId = null;
                $('#optimizeDialog').modal('hide');
                $scope.query();
            });
        };

        $scope.init();
        $scope.initEvent();
        $scope.query();
    }]);
});